package com.qkl.upload.publics.service;

import com.alibaba.fastjson.JSON;
import com.qkl.upload.publics.dto.BusinessDTO;
import com.qkl.upload.publics.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class UploadFileService {

    private static final String URL_XIAJIANG_APP = "https://xiajiang.qkl88.cn/xiajiangapp/application";

    @Value("${root.uploadPath}")
    private String uploadRoot;


    /**
     * 上传文件
     * @param fileDTO
     * @return
     */
    public BusinessDTO<Object> uploadFile(UploadFileDTO fileDTO){
        Map<String, Object> reqeustBody = fileDTO.getParams();
        log.info("====uploadFile.fileDTO.params={}",fileDTO.getParams());
        log.info("====uploadFile.fileDTO.headers={}",fileDTO.getHeaders());
        if(null == fileDTO){
            return BusinessDTO.failBusiness("文件上传失败");
        }
        Map<String,Object> params = fileDTO.getParams();
        if(ObjectUtils.isNotEmpty(params)){
            params.put("fileSuffix",fileDTO.getSuffixName());
        }
        String url = URL_XIAJIANG_APP + "/uploadFileCheckSubmit";
        if(fileDTO.uploadTypeBreed()){
            url = URL_XIAJIANG_APP + "/openApi/uploadCommonFileSubmit";
        }
        if (reqeustBody.containsKey("uploadType")) {
            String uploadType = String.valueOf(reqeustBody.getOrDefault("uploadType", ""));
            url = "3".equalsIgnoreCase(uploadType) ? URL_XIAJIANG_APP + "/workflow/uploadFile" : url;
        }
        HttpResponse<String>  response = HttpUtils.postRequestJson(url,fileDTO.getHeaders(),fileDTO.getParams());
        log.info("====uploadFile.response={}",response);
        if(!response.isSuccess()){
            return BusinessDTO.failBusiness("文件上传失败：" + response.getMsg() );
        }
        String dataJson = response.getData();
        if(StringUtils.isEmpty(dataJson)){
            return BusinessDTO.failBusiness("文件上传失败：虾匠系统返回异常");
        }
        Result result = JSON.parseObject(dataJson,Result.class);
        if(!result.resultSuccess()){
            return BusinessDTO.failBusiness("文件上传失败：" + result.getMessage());
        }
        Map<String,String> dataPram = (Map<String,String>)result.getData();
        String filePathName = "filePath";
        String fileDirPathName = "fileDirPath";
        if(ObjectUtils.isEmpty(dataPram) || !dataPram.containsKey(filePathName) || !dataPram.containsKey(fileDirPathName) ){
            return BusinessDTO.failBusiness("文件上传失败,文件路为空");
        }
        String filePath = dataPram.get(filePathName);
        String fileDirPath = dataPram.get(fileDirPathName);
        String uploadId = dataPram.get("uploadId");
        String uploadDirPath = uploadRoot + fileDirPath;
        String uploadPath = uploadRoot + filePath;

        log.info("====uploadFile.uploadDirPath={},uploadPath={}",uploadDirPath,uploadPath);

        FileOutputStream stream = null;
        try {
            File fileDir = new File(uploadDirPath);
            if(!fileDir.exists()){
                log.info("create fileDir.success={}",fileDir.mkdirs());
            }
             stream = new FileOutputStream(uploadPath);
             stream.write(fileDTO.getContent());
             stream.flush();
             Map<String,Object> map = new HashMap<>();
             map.put("uploadId",uploadId);
             return BusinessDTO.sucessBusiness(map,"文件上传成功");
        }catch (Exception e){
            e.printStackTrace();
            return BusinessDTO.failBusiness("文件上传保存失败");
        }finally {
            if(null != stream){
                try {
                    stream.close();
                }catch (Exception exception){

                }
            }
        }
    }

    /**
     *共公文件删除
     * @param uploadId
     * @return
     */
    public BusinessDTO<Object> deleteCommonFile(String uploadId){
        uploadId = StringUtils.trimToEmpty(uploadId);
        if(StringUtils.isEmpty(uploadId)){
            return BusinessDTO.failBusiness("上传id不能为空");
        }
        Map<String,String> params = new HashMap<>();
        params.put("uploadId",uploadId);
        String url = URL_XIAJIANG_APP + "/openApi/deleteCommonFile";
        HttpResponse<String>  response = HttpUtils.postRequestJson(url,params);
        log.info("====deleteCommonFile.response={}",response);
        if(!response.isSuccess()){
            return BusinessDTO.failBusiness("共公文件删除失败：" + response.getMsg() );
        }
        String dataJson = response.getData();
        if(StringUtils.isEmpty(dataJson)){
            return BusinessDTO.failBusiness("文件上传失败：虾匠系统返回异常");
        }
        Result result = JSON.parseObject(dataJson,Result.class);
        if(!result.resultSuccess()){
            return BusinessDTO.failBusiness("文件上传失败：" + result.getMessage());
        }
        Map<String,String> dataPram = (Map<String,String>)result.getData();
        String filePathName = "filePath";
        String filePath = dataPram.get(filePathName);
        String uploadPath = uploadRoot + filePath;
        log.info("====deleteCommonFile.uploadPath={}",uploadPath);
        File file = new File(uploadPath);
        if(file.exists() && file.isFile()){
            file.delete();
            log.info("====deleteCommonFile finish!uploadPath={}",uploadPath);
        }
        Map<String,Object> map = new HashMap<>();
        map.put("uploadId",uploadId);
        return BusinessDTO.sucessBusiness(map,"删除文件成功");
    }

    /**
     *删除查料台过期文件
     */
    public BusinessDTO<Object> deleteCheckExpireVideo(){
        String url = URL_XIAJIANG_APP + "/openApi/queryExpireCheckDirectory";
        HttpResponse<String>  response = HttpUtils.getRequest(url,null);
        BusinessDTO<Result> resultBusiness = parseXiaJiangResult(response);
        if( !resultBusiness.isSucess()){
            return BusinessDTO.failBusiness(resultBusiness.getMessage());
        }
        Result result = resultBusiness.getBusinessObject();
        if( !result.resultSuccess()){
            return BusinessDTO.failBusiness(result.getMessage());
        }
        Map<String,Object> dataPram = (Map<String,Object>)result.getData();
        List<String> directoryList = (List<String>)dataPram.get("directoryList");
        log.info("======deleteCheckExpireVideo.directoryList={}",directoryList);
        if(ObjectUtils.isNotEmpty(directoryList)){
            for (String subDirectory : directoryList) {
                deleteDirectory(subDirectory);
            }
        }
        return BusinessDTO.sucessBusiness(new HashMap<>(),"删除查料台过期文件");
    }


    private void deleteDirectory(String subDirectory){
        FileHelperUtils.deleteDirectory(uploadRoot,subDirectory);
    }

    private static BusinessDTO<Result> parseXiaJiangResult(HttpResponse<String> response ){
        log.info("====parseXiaJiangResult.response={}",response);
        if(!response.isSuccess()){
            return BusinessDTO.failBusiness("调用虾匠失败：" + response.getMsg() );
        }
        String dataJson = response.getData();
        if(StringUtils.isEmpty(dataJson)){
            return BusinessDTO.failBusiness("调用虾匠失败：虾匠系统返回异常");
        }
        Result result = JSON.parseObject(dataJson,Result.class);
        return BusinessDTO.sucessBusiness(result);
    }


    public BusinessDTO complete(UploadFileDTO fileDTO) {
        log.info("====uploadFile.fileDTO.params={}",fileDTO.getParams());
        log.info("====uploadFile.fileDTO.headers={}",fileDTO.getHeaders());
        if(null == fileDTO){
            return BusinessDTO.failBusiness("文件上传失败");
        }
        Map<String,Object> params = fileDTO.getParams();
        if(ObjectUtils.isNotEmpty(params)){
            params.put("fileSuffix",fileDTO.getSuffixName());
        }
        String url = URL_XIAJIANG_APP + "/uploadFileCheckSubmit";
        if(fileDTO.uploadTypeBreed()){
            url = URL_XIAJIANG_APP + "/openApi/uploadCommonFileSubmit";
        }
        HttpResponse<String>  response = HttpUtils.postRequestJson(url,fileDTO.getHeaders(), fileDTO.getParams());
        log.info("====uploadFile.response={}",response);
        if(!response.isSuccess()){
            return BusinessDTO.failBusiness("文件上传失败：" + response.getMsg() );
        }
        String dataJson = response.getData();
        if(StringUtils.isEmpty(dataJson)){
            return BusinessDTO.failBusiness("文件上传失败：虾匠系统返回异常");
        }
        Result result = JSON.parseObject(dataJson,Result.class);
        if(!result.resultSuccess()){
            return BusinessDTO.failBusiness("文件上传失败：" + result.getMessage());
        }
        Map<String,String> dataPram = (Map<String,String>)result.getData();
        String filePathName = "filePath";
        String fileDirPathName = "fileDirPath";
        if(ObjectUtils.isEmpty(dataPram) || !dataPram.containsKey(filePathName) || !dataPram.containsKey(fileDirPathName) ){
            return BusinessDTO.failBusiness("文件上传失败,文件路为空");
        }
        String filePath = dataPram.get(filePathName);
        String fileDirPath = dataPram.get(fileDirPathName);
        String uploadId = dataPram.get("uploadId");
        String uploadDirPath = uploadRoot + fileDirPath;
        String uploadPath = uploadRoot + filePath;

        log.info("====uploadFile.uploadDirPath={},uploadPath={}",uploadDirPath,uploadPath);

        FileOutputStream stream = null;
        try {
            File fileDir = new File(uploadDirPath);
            if(!fileDir.exists()){
                log.info("create fileDir.success={}",fileDir.mkdirs());
            }
            stream = new FileOutputStream(uploadPath);
            stream.write(fileDTO.getContent());
            stream.flush();
            Map<String,Object> map = new HashMap<>();
            map.put("uploadId",uploadId);
            return BusinessDTO.sucessBusiness(map,"文件上传成功");
        }catch (Exception e){
            e.printStackTrace();
            return BusinessDTO.failBusiness("文件上传保存失败");
        }finally {
            if(null != stream){
                try {
                    stream.close();
                }
                catch (Exception ignored){

                }
            }
        }
    }
}
